//
//  FormTableViewController.m
//  zealcomm4.1Demo
//
//  Created by zealcomm user on 2020/7/22.
//  Copyright © 2020 zealcomm user. All rights reserved.
//

#import "FormTableViewController.h"

@interface FormTableViewController ()

@property(strong,nonatomic)NSMutableArray *fieldsArray;

@end

@implementation FormTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    NSLog(@"form,data=>%@",self.formTemplateData);
    
    self.fieldsArray = [NSMutableArray array];
    
    for (NSDictionary *dic in [self.formTemplateData valueForKey:@"fields"]) {
        [self.fieldsArray addObject:dic];
    }
}

-(void)submit:(id)sender{
    
    //获取cell里面的内容
    NSIndexPath *path = [NSIndexPath indexPathForRow:0 inSection:0];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:path];
    NSMutableDictionary *para = [NSMutableDictionary dictionaryWithDictionary:@{
        @"sessionId":self.sessionId,
        @"formTemplateId":[self.formTemplateData valueForKey:@"_id"],
    }];
    NSMutableDictionary *fields = [NSMutableDictionary dictionary];
    if (cell) {
        for (int i = 0; i<self.fieldsArray.count; i++) {
            NSDictionary *field = [self.fieldsArray objectAtIndex:i];
            for (UITextField *input in cell.contentView.subviews) {
                if ([input isKindOfClass:[UITextField class]]) {
                    if ([input.text isEqualToString:@""]) {
                        NSLog(@"请完善信息～～～");
                        return;
                    }else{
                        if (input.tag == i) {
                            [fields setValue:input.text forKey:[field valueForKey:@"name"]];
                        }
                    }
            }
            
        }
    }
        [para setValue:fields forKey:@"fields"];
        NSLog(@"...para%@",para);
        [self.ivcsSdk uploadFormDataWithSessionId:self.sessionId url:@"https://ivcs-demo.zealcomm.cn/api/applications" parameter:para onSuccess:^(id _Nonnull res) {
            NSLog(@"succeess,11,,%@",res);
            [self.navigationController popViewControllerAnimated:false];
            [self.ivcsSdk sendTextMessage:@"inputformsuccess" toRoles:@"agents" onSuccess:^{
                NSLog(@"...33success");
            } onFailure:^(NSError * _Nonnull error) {
                 NSLog(@"...22error,%@",error);
            }];
        } onFailure:^(NSError * _Nonnull error) {
            NSLog(@"...11error,%@",error);
        }];
    }
}

-(NSDictionary*)returnDictionaryWithDataPath:(NSData*)data
{
    NSString *receiveStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

    NSData * datas = [receiveStr dataUsingEncoding:NSUTF8StringEncoding];

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:datas options:NSJSONReadingMutableLeaves error:nil];

    return jsonDict;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return self.fieldsArray.count*50;
}


-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return  80;
}


-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    CGFloat screenWidth = self.tableView.frame.size.width;
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake((screenWidth-300)/2, 20, 300, 40)];
    [btn setTitle:@"提交" forState:UIControlStateNormal];
    [btn setBackgroundColor:[UIColor redColor]];
    UIView *footView = [[UIView alloc] init];
    [btn addTarget:self action:@selector(submit:) forControlEvents:UIControlEventTouchUpInside];
    btn.layer.masksToBounds = true;
    btn.layer.cornerRadius = 20;
    [footView addSubview:btn];
    return footView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"form"];
    
    CGFloat width = self.tableView.frame.size.width;
    CGFloat height = 40;
    CGFloat iWidth = 300;
    for (int i = 0; i<self.fieldsArray.count; i++) {
        NSDictionary *field = [self.fieldsArray objectAtIndex:i];
        CGFloat y = i*50+10;
        CGFloat x = (width-300)/2;
        UITextField *input = [[UITextField alloc] initWithFrame:CGRectMake(x, y, iWidth, height)];
        input.borderStyle = UITextBorderStyleRoundedRect;
        input.placeholder = [field valueForKey:@"name"];
        input.tag = i;
        [cell.contentView addSubview:input];
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/


@end
